package com.tmc.service.intair;

import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.tmc.bean.common.CommonResult;
import com.tmc.bean.common.ContextInfo;
import com.tmc.bean.common.Pagination;
import com.tmc.bean.intair.EthFare;
import com.tmc.bean.intair.EthFlight;
import com.tmc.bean.intair.EthShoppingReq;
import com.tmc.constant.FareConstant;
import com.tmc.constant.FareConstant.PolicyStatus;
import com.tmc.dao.impl.SettleProfitDaoImpl;
import com.tmc.entity.intair.SettleProfit;
import com.tmc.util.ObjectUtil;

@Service
@Transactional
public class SettleProfitServiceImpl {

	private Log logger = LogFactory.getLog(SettleProfitServiceImpl.class);

	@Autowired
	private SettleProfitDaoImpl policyDao;
	
	public List<SettleProfit> findPolicys(ContextInfo context, EthShoppingReq req) {
		List<SettleProfit> policys = policyDao.findPolicys(context, req);
		return policys;
	}

	public Pagination<SettleProfit> findPolicysByCon(ContextInfo context, SettleProfit cond, int pageIndex,
			int pageSize) {
		Pagination<SettleProfit> result = policyDao.findPolicysByCon(context, cond, pageIndex, pageSize);
		this.setExtInfo(result);
		return result;
	}

	public SettleProfit getById(ContextInfo context, Long policyId) {
		SettleProfit result = policyDao.getById(policyId);
		this.setExtInfo(result);
		return result;
	}

	public CommonResult changePolicyStatus(ContextInfo context, Long policyId, String toStatus) {
		SettleProfit policy = policyDao.getById(policyId);
		if (policy != null) {
			ObjectUtil.updateBaseInfo(policy, context);
			policy.setStatus(toStatus);
			policyDao.update(policy);
		}
		return CommonResult.makeSuccess();
	}

	public CommonResult changePolicysStatus(ContextInfo context, String policyIds, String toStatus) {
		if (ObjectUtil.noText(policyIds)) {
			return CommonResult.makeFail("请选择至少一条政策");
		}
		for (String policyId : policyIds.split(",")) {
			this.changePolicyStatus(context, Long.valueOf(policyId), toStatus);
		}
		return CommonResult.makeSuccess();
	}

	public CommonResult deletePolicy(ContextInfo context, Long policyId) {
		SettleProfit policy = policyDao.getById(policyId);
		if (policy != null) {
			ObjectUtil.updateBaseInfo(policy, context);
			policy.setEnabledFlag("N");
			policyDao.update(policy);
		}
		return CommonResult.makeSuccess("删除成功！");
	}

	public CommonResult deletePolicys(ContextInfo context, String policyIds) {
		if (!ObjectUtil.hasText(policyIds)) {
			return CommonResult.makeSuccess();
		}
		for (String str : policyIds.split(",")) {
			CommonResult cr = this.deletePolicy(context, Long.valueOf(str));
			if (!cr.isSuccess()) {
				return cr;
			}
		}
		return null;
	}

	public CommonResult savePolicy(ContextInfo context, SettleProfit policy) {
		//
		CommonResult check = this.checkPolicy(policy);
		if (!check.isSuccess()) {
			return check;
		}
		// 处理字段
		this.beforeSave(policy);
		// 保存
		if (policy.getPolicyId() == null) {
			try {
				ObjectUtil.setBaseInfo(policy, context);
				policy.setStatus(PolicyStatus.DOWN.getStatus());
				policyDao.insert(policy);
			} catch (Exception e) {
				logger.error("保存政策失败！", e);
				return CommonResult.makeFail(e.getMessage());
			}
		} else {
			// 编辑
			try {
				SettleProfit dbPolicy = policyDao.getById(policy.getPolicyId());
				if (dbPolicy != null) {
					ObjectUtil.copyProperties(policy, dbPolicy,
							new String[] { "createdBy", "creationDate", "policyId", "status", "enabledFlag" });
				}
				if (!ObjectUtil.hasText(policy.getStatus())) {
					dbPolicy.setStatus(PolicyStatus.DOWN.getStatus());
				}
				ObjectUtil.updateBaseInfo(dbPolicy, context);
				policyDao.update(dbPolicy);
			} catch (Exception e) {
				logger.error("拷贝对象错误！", e);
				return CommonResult.makeFail("拷贝对象错误！");
			}
		}
		return CommonResult.makeSuccess();
	}
	
	private void beforeSave(SettleProfit policy) {
		policy.setAirline(ObjectUtil.toUpperCase(policy.getAirline()));
	}

	private CommonResult checkPolicy(SettleProfit policy) {
		return CommonResult.makeSuccess();
	}

	private void setExtInfo(Pagination<SettleProfit> result) {
		if (result == null || result.getItems() == null || result.getItems().isEmpty()) {
			return;
		}
		for (SettleProfit policy : result.getItems()) {
			this.setExtInfo(policy);
		}
	}
	
	private void setExtInfo(SettleProfit policy) {
		if (policy == null){
			return;
		}
		policy.setStatusName(FareConstant.getStatusName(policy.getStatus()));
		policy.setPlatformName(this.getPlatformName(policy.getPlatform()));
	}
	
	private String getPlatformName(String platform){
		if (ObjectUtil.noText(platform)){
			return platform;
		}
		StringBuilder sb = new StringBuilder();
		for (String str : platform.split(",")){
			sb.append(FareConstant.getPlatformName(str)).append("/");
		}
		return sb.toString();
	}

	public List<EthFare> matchPolicy(List<EthFare> fares, Map<String, Map<String, EthFlight>> avMap, List<SettleProfit> policys) {
		if (policys == null || policys.isEmpty() || fares == null || fares.isEmpty())
			return fares;
		for (EthFare fare : fares) {
			for (SettleProfit policy : policys) {
				// 是否匹配到政策
				if (!this.isMatch(fare, policy))
					continue;
				// 计算运价
				this.calculateCommision(fare, policy);
			}
		}
		return fares;
	}

	private boolean isMatch(EthFare fare, SettleProfit policy) {
		// 航司是否匹配
		if (!this.isAirlineMatch(fare, policy))
			return false;
		// TODO 其他条件是否匹配

		return true;
	}


	private boolean isAirlineMatch(EthFare fare, SettleProfit policy) {
		String ticketingAirline = fare.getTicketingCarrier();
		String airline = policy.getAirline();
		if (airline.equalsIgnoreCase(ticketingAirline))
			return true;
		return false;
	}

	private void calculateCommision(EthFare fare, SettleProfit policy) {
		Double ticketPrice = fare.getTicketPrice();
		Double q = fare.getQ();
		Double profit = policy.getProfit();// %
		Double profitPrice = policy.getProfitPrice();
		// 留点留钱
		Integer totalProfit = (int)Math.ceil(ticketPrice * profit / 100 + profitPrice);
		fare.setSearchTicketPrice(Math.ceil(ticketPrice + q + totalProfit));
		fare.setSettleProfitId(policy.getPolicyId());
		fare.setSettleProfit(totalProfit);
		fare.setTotalAmount(fare.getSearchTicketPrice() + fare.getTax());
	}

}
